/*
*********************************
*@author: junjunwang@wlrobo.com
*@brief:  西湖机器人信息管理系统
*@version: 1.0.0
*@date: 2024/5/7 10:18
1.
********************************
*/
package main

import (
	"github.com/panjf2000/ants/v2"
	"github.com/sirupsen/logrus"
	"go.uber.org/zap"
	"os"
	"os/signal"
	"runtime"
	"sync"
	"syscall"
	"wlrIms/config"
	"wlrIms/db"
	"wlrIms/file"
	"wlrIms/handler"
	"wlrIms/log"
)

var cfg config.Cfg

// 初始化
func init() {
	//加载配置
	JsonParse := config.NewJsonStruct()
	cfg = JsonParse.LoadCfg() //获取结构体信息
	logDir := cfg.Dir + "/Log"
	if len(cfg.Dir) > 0 {
		//创建目录
		fileHandler := file.NewFileStruct()
		if err := fileHandler.CreteFile(logDir); err != nil {
			logrus.Fatalf("无法创建日志目录：%v", err)
		}
	}
	// 配置日志
	logrus.Info("Log Dir : ", logDir)
	logFile := logDir + "/wlrIms.log"
	log.ConfigLog(logFile)
	db.InitDB()
}

// 启动startServer
func startServer() {
	pServer := handler.NewServer()
	pServer.Start()
}
func main() {
	logrus.Info("Starting wlrIms Server")
	runtime.GOMAXPROCS(runtime.NumCPU())
	// 创建线程池
	poolSize := runtime.NumCPU() * 4 // 设置线程池大小为CPU核心数的4倍
	var err error
	p, err := ants.NewPool(poolSize)
	if err != nil {
		logrus.Fatalf("Failed to create goroutine pool: %v", err)
	}
	defer p.Release()

	var wg sync.WaitGroup
	wg.Add(1)
	// 并发执行Server和Router任务
	if err := p.Submit(func() {
		defer wg.Done()
		startServer()
	}); err != nil {
		logrus.Fatalf("Failed to submit server job to pool: %v", err)
	}
	// 捕捉退出信号
	signalCh := make(chan os.Signal, 1)
	signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
	sig := <-signalCh
	logrus.Info("Received signal:", zap.Any("signal", sig))
	// 等待任务完成
	wg.Wait()
}
